#include <vector>
#include <list>
#include <map>
#include <set>
#include <queue>
#include <deque>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <fstream>
#include <set>

using namespace std;
struct ListNode {
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};

//add better code
ListNode* reverse(ListNode *head, ListNode *nextStart)
{
    ListNode *prev = NULL, *saveHead = head;
    while (head != nextStart) {
        ListNode *nxt = head->next;
        head->next = prev;
        prev = head;
        head = nxt;    
    }   
    saveHead->next = nextStart; 
    return prev;
}
 

class Solution {
public:
    ListNode *reverseKGroup(ListNode *head, int k) {
        ListNode Dummy(0);
         int m;
        ListNode *h = &Dummy;
        h->next = head;
        ListNode *preEnd = h, *nextStart, *curStart;;
        while (1) {
            m = k;
            nextStart = preEnd->next;
            curStart = preEnd->next;
            while(nextStart && m-- > 0) {
                nextStart = nextStart->next;
            }
            if (m > 0) break;
            preEnd->next = reverse(preEnd->next, nextStart);
            preEnd = curStart;
        }

        return h->next;
    }

};



ListNode *newList(int data[], int index, int size)
{
    ListNode *node = NULL;
    if (index == size)
        return node;

    node = new ListNode(data[index]);
    node->next = newList(data, index+1, size);

    return node;
}

//test on 1337 online judge and pass all the test
int main(int argc, char **argv)
{

    Solution2 mySolution;
    cout << "-----------------Test 1--------------------" << endl;
    vector<ListNode *> myList;
    int data[] = {1};
    ListNode *list1, *list2;
    list1 = newList(data, 0, sizeof(data)/sizeof(int));
    ListNode *list = mySolution.reverseKGroup(list1, 1);
    while(list) {
        cout << list->val << " ";
        list= list->next;
    }
    cout << endl;
    cout << "-----------------Test 2--------------------" << endl;
    list1 = newList(data, 0, sizeof(data)/sizeof(int));
    list = mySolution.reverseKGroup(list1, 9);
    while(list) {
        cout << list->val << " ";
        list= list->next;
    }
    cout << endl;

    cout << "-----------------Test 3--------------------" << endl;


    cout << "-----------------Test 4--------------------" << endl;


    cout << "-----------------Test 5--------------------" << endl;



}
